package common.util;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;

public class MapUtil {

    /**
     * JDK8
     * 按照Key排序
     *
     * @param map map数据
     * @param asc 是否升序
     * @param <K> Key
     * @param <V> Value
     * @return Map<K, V>
     */
    public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean asc) {
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Map.Entry<K, V>> stream = map.entrySet().stream();
        if (asc) {
            stream.sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        } else {
            stream.sorted(Map.Entry.<K, V>comparingByKey().reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        return result;
    }

    /**
     * JDK8
     * 按照Value排序
     *
     * @param map map数据
     * @param asc 是否升序
     * @param <K> Key
     * @param <V> Value
     * @return Map<K, V>
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean asc) {
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Map.Entry<K, V>> stream = map.entrySet().stream();
        if (asc) //升序
        {
            stream.sorted(Map.Entry.comparingByValue()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        } else //降序
        {
            stream.sorted(Map.Entry.<K, V>comparingByValue().reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        return result;
    }


}

